package edu.chl.vrangogym.auth;

import edu.chl.vrangogym.persistence.entities.User;
import edu.chl.vrangogym.persistence.entities.enums.Permissions;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Filter for separating Admin from users and guests. A user or guest trying to access a 
 * restricted area will be redirected to the login page.
 * @author Anders
 */
public class AdminFilter implements Filter {

    private FilterConfig config;

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        String root = req.getServletContext().getContextPath();
        User user = (User) ((HttpServletRequest) req).getSession()
                .getAttribute("Auth.user");
        if (user == null) {
            ((HttpServletResponse) resp).sendRedirect(root + "/index.xhtml");
        } else {
            if(user.getPermissions() != Permissions.ADMIN) {
                ((HttpServletResponse) resp).sendRedirect(root + "/index.jsf");
            }
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void destroy() {
        config = null;
    }
}